package coreservice

import (
	"core/coreqto"
	"core/corestruct"
	"gorm.io/gorm"
)

type PageService[T any] struct {
}

func (p *PageService[T]) Page(qto *coreqto.BasePageQto, ctx *corestruct.HttpContext, db *gorm.DB) (*corestruct.Page[T], error) {
	var r = &corestruct.Page[T]{}
	r.TotalRow = 0
	r.PageNumber = qto.Page
	r.PageSize = qto.PageSize
	r.Records = make([]T, 0)
	var tx = db.Count(&r.TotalRow)
	if tx.Error != nil {
		return nil, tx.Error
	}
	if 0 == r.TotalRow {
		return r, nil
	}
	if "" != qto.SortFields {
		tx = tx.Order(Sort.GetSort(qto.SortFields))
	} else {
		tx = tx.Order("id desc")
	}

	tx = tx.Offset(r.GetOffset()).Limit(int(r.PageSize)).
		Find(&r.Records)

	if tx.Error != nil {
		return nil, tx.Error
	}

	return r, nil
}
